import { defineStore, acceptHMRUpdate } from 'pinia'

export interface GlobalStatus {
  opNames: { [key: string]: boolean }
  requestNumber: number
  error: {
    status: boolean
    message?: string
  }
}

export const useGlobalStore = defineStore('global', {
  state: (): GlobalStatus => ({
    requestNumber: 0,
    opNames: {},
    error: {
      status: false
    }
  }),

  getters: {
    isLoading: state => {
      return state.requestNumber > 0
    },

    isOpLoading: state => (opName: string) => {
      return state.opNames[opName] || false
    }
  },

  actions: {
    startLoading(payload?: { opName: string }) {
      this.requestNumber++
      if (payload) {
        this.opNames[payload.opName] = true
      }
    },

    finishLoading(payload?: { opName: string }) {
      // setTimeout(() => {
      //   this.requestNumber--
      //   if (payload) {
      //     delete this.opNames[payload.opName]
      //   }
      // }, 1000)

      this.requestNumber--
      if (payload) {
        delete this.opNames[payload.opName]
      }
    },

    setError(error: { status: boolean; message?: string }) {
      this.error = error
    }
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useGlobalStore, import.meta.hot))
}
